package cn.z2huo.core.web;

import cn.z2huo.core.status.StatusCode;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.Assert;

import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * <p>
 *
 * @author z2huo
 */
@Data
@Accessors(chain = true)
public class ResponseMessage<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1301540767120258751L;

    /**
     * <p>事务代码
     */
    private String transactionCode;

    /**
     * <p>消息编码
     */
    private String code;

    /**
     * <p>消息内容
     */
    private String content;

    /**
     * <p>是否成功
     */
    private boolean success;

    /**
     * <p>传递的业务数据
     */
    private T data;

    /**
     * <p>处理时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime dateTime;

    public static <T> ResponseMessage<T> error(ResponseMessage<?> result) {
        return error(result.getCode(), result.getContent());
    }

    public static <T> ResponseMessage<T> error(String code, String content) {
        Assert.isTrue(!StatusCode.SUCCESS.getCode().equals(code), "code 必须是错误的！");

        ResponseMessage<T> result = new ResponseMessage<>();
        result.setCode(code).setContent(content).setSuccess(false);
        return result;
    }

    public static <T> ResponseMessage<T> error(StatusCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMessage());
    }

    public static <T> ResponseMessage<T> success(T data) {
        ResponseMessage<T> result = new ResponseMessage<>();
        result.setCode(StatusCode.SUCCESS.getCode()).setData(data).setContent("success").setSuccess(true);
        return result;
    }

}
